package com.lxr0860.lxr0860production_test;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import androidx.annotation.Nullable;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.lxr0860.lxr0860production_test.base.DevNumberUtils;
import com.lxr0860.lxr0860production_test.bean.TestRecorde;
import com.lxr0860.lxr0860production_test.db.MyRoomDatabase;
import com.lxr0860.lxr0860production_test.db.tb.DevInfo;
import com.lxr0860.lxr0860production_test.utils.Contants;
import com.lxr0860.lxr0860production_test.utils.SharedPreferencesUtils;
import com.lxr0860.lxr0860production_test.utils.ThreadPool;
import com.lxr0860.lxr0860production_test.utils.ToastUtils;
import com.lxr0860.lxr0860production_test.view.TableView;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Objects;

public class UpdateRecordeActivity extends Activity {


    private String formatDate;
    private Socket socket = null;
    private Button upBtn;
    private WifiManager wifiManager;
    private String testState;
    private String bindInfo;
    private String errorInfo;
    private String testData;
    private TableView mTableView;
    private ProgressDialog dialog;
    private DevNumberUtils devNumberUtils;

    private Button resetBtn;
    String tips = "";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_codebinding);
        initView();
        initData();
        initEvent();
    }

    private void initEvent() {
        resetBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String updateState = SharedPreferencesUtils.getData(UpdateRecordeActivity.this, Contants.UpdateDEVInfoState, "fail");

                if (updateState.equals("true")) {
                    tips = "是否恢复出厂设置？";
                }else{
                    tips = "未上传设备信息";
                }
                AlertDialog.Builder builder = new AlertDialog.Builder(UpdateRecordeActivity.this);
                builder.setTitle("提示！！！")
                        .setMessage(tips);

                // 确定按钮
                builder. setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        resetSystem();
                    }
                });

                AlertDialog alert = builder.create();  // 创建 AlertDialog 对象
                alert.show();    // 显示对话框
            }
        });
        testState = SharedPreferencesUtils.getData(this, Contants.TestState, "fail");
        upBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (testState.equals("fail")) {
                    ToastUtils.showMessage("存在漏测，或测试失败项，请重确认");
                }
                ThreadPool.getInstance().execute(new Runnable() {
                    @Override
                    public void run() {
                        updateRecorde();
                    }
                });
            }
        });
    }

    private void initView() {
        mTableView = (TableView) findViewById(R.id.tabv_recorde_table);
        upBtn = findViewById(R.id.upBtn);
        resetBtn = findViewById(R.id.resetBtn);
    }

    private void initData() {
        devNumberUtils = DevNumberUtils.getInstance(this);
        dialog = ProgressDialog.show(this, "", "正在加载数据", true);

        mTableView.clearTableContents();
        mTableView.setVisibility(View.VISIBLE);
        mTableView.setHeader("配置项", "配置信息");
        mTableView.setColumnWeights(4, 6, 0);
//        mTableView.setColumnWeights(2,8);
        //打开WiFi，判断是否连接
        wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        wifiManager.setWifiEnabled(true);
        ThreadPool.getInstance().execute(new Runnable() {
            @Override
            public void run() {
                getUpdateData();
            }
        });
    }

    private void updateRecorde() {
        //初始化socket，并建立链接
        if (conService()) {
            sendData(bindInfo, "设备信息");
            sendData(testData, "测试记录");
        }
    }

    private void getUpdateData() {
        //获取绑定关系
//        DevInfo devInfo = MyRoomDatabase.getInstance().devInfoDao().queryDevInfo();
        DevInfo devInfo = new DevInfo();
        //获取当前时间
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");
        Date date = new Date(System.currentTimeMillis());
        formatDate = simpleDateFormat.format(date);
        //数据类型
        devInfo.setDataType("1");
        //设备类型
        devInfo.setEquipmentModel(Build.MODEL);
        //系统版本
        devInfo.setSystemVersion(Build.DISPLAY.equals("") ? "fail" : Build.DISPLAY);
        //蓝牙mac地址
        devInfo.setBtMac(devNumberUtils.getBTMac());
        //获取FlashID
        devInfo.setFlashID(devNumberUtils.getFlashID());
        //获取IMEI号
        devInfo.setIMEI(devNumberUtils.getIMEI());
        //获取wifiMac地址
        devInfo.setWifiMac(devNumberUtils.getWifiMac());
        devInfo.setUpdateDate(formatDate);
        //起爆器编号
        devInfo.setDetonatorNo(devNumberUtils.getDetonatorno());
        //终端编号
        devInfo.setTerminalNo(devNumberUtils.getTerNo());
        //sam卡编号
        devInfo.setSamNo(devNumberUtils.getSamSN());
        //获取MAC版本
        devInfo.setMCUVS(devNumberUtils.getMCUVS());
        //获取App版本
        devInfo.setTestSoftVS(devNumberUtils.getAPPVS());
        //获取序列号
        devInfo.setSerialNo(devNumberUtils.getDeviceSN());
        //获取条码头型号
        devInfo.setBarcodeModuleModel(devNumberUtils.getBarcodeID());
        //获取相机和tp相关
        String[] split = devNumberUtils.getCamera_TPInfo();
        if (split.length >= 13) {
            devInfo.setFrontCameraModel(split[12].equals("") ? "fail" : split[12]);
            devInfo.setRearCameraModel(split[9].equals("") ? "fail" : split[9]);
            devInfo.setLCDScreenModel(split[1].equals("") ? "fail" : split[1]);
            //TP
            devInfo.setTouchScreenModel(split[3].equals("") ? "fail" : split[3]);
        }


        bindInfo = new Gson().toJson(devInfo);
        Log.e("bindInfo", bindInfo);
        Map bindInfoMap = (Map) JSON.parse(bindInfo);
        for (String title : Contants.infoTitlesTest) {
            String error = (String) bindInfoMap.get(title);
            if (error != null && error.equals("fail")) {
                errorInfo = title + ":" + error + "\n";
            }
            mTableView.addContent(title, bindInfoMap.get(title).toString());
        }

        //数据库更新绑定关系
        MyRoomDatabase.getInstance().devInfoDao().insertDevInfo(devInfo);

        //获取测试记录
        testData = getTestRecords();
        Log.e("testData", testData);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mTableView.refreshTable();
                ToastUtils.showMessage("设备信息存在异常，请确认！！！");
            }
        });
        dialog.dismiss();
    }

    private String getTestRecords() {

        TestRecorde testRecorde = new TestRecorde();
        testRecorde.setDataType("2");
        testRecorde.setTestDate(formatDate);
        testRecorde.setFlashID(devNumberUtils.getFlashID());

        testRecorde.setTestState(testState);

        String zzcj = SharedPreferencesUtils.getData(this, Contants.ZZCJ, "");
        String zdcs = SharedPreferencesUtils.getData(this, Contants.ZDCS, "");
        String fscs = SharedPreferencesUtils.getData(this, Contants.FSCS, "");
        String dwcs = SharedPreferencesUtils.getData(this, Contants.DWCS, "");
        String gwcs = SharedPreferencesUtils.getData(this, Contants.GWCS, "");
        String cpjy = SharedPreferencesUtils.getData(this, Contants.CPJY, "");
//        String cpcj = SharedPreferencesUtils.getData(this, Contants.CPCJ, "");

        testRecorde.setZZCJ(zzcj);
        testRecorde.setZDCS(zdcs);
        testRecorde.setFSCS(fscs);
        testRecorde.setDWCS(dwcs);
        testRecorde.setGWCS(gwcs);
        testRecorde.setCPJY(cpjy);
//        testRecorde.setCPCJ(cpcj);
        String testData = new Gson().toJson(testRecorde);
        return testData;
    }

//'01.Wrong data type 错误的数据类型
//'02.Equipment information duplication 设备信息重复
//'03.Test Record duplication. 测试记录重复
//'04.Equipment information DataBase Error.（后面有错误描述信息）设备信息数据库错误
//'05.Test Record DataBase Error.（后面有错误描述信息）测试记录数据库错误
//'09.Unknown database error.（后面有错误描述信息）未知的数据库错误

    private synchronized void sendData(String sendData, String tips) {
        try {
            //上传数据
            if (socket.isConnected() && !socket.isClosed()) {
                OutputStream osSend = socket.getOutputStream();  //发送byte字节数据
                InputStream isRead = socket.getInputStream();

                osSend.write(sendData.getBytes());  //写byte字节数据
                //准备接收服务器反馈dateok
                String sendResult = "";
                // 客户端接收服务器端的响应，读取服务器端向客户端的输入流
                long startSendTime = SystemClock.elapsedRealtime();
                while (true) {
                    if (isDestroyed()) {
                        return;
                    }
                    if (SystemClock.elapsedRealtime() - startSendTime >= 3 * 1000) {
                        break;
                    }
                    if (isRead.available() > 0) {
                        break;
                    }
                }
                byte[] sendBuf = new byte[isRead.available()];
                isRead.read(sendBuf);
                sendResult = new String(sendBuf);
                Log.e("sendRes", sendResult);
                Map parse = (Map) JSON.parse(sendResult);
                if (parse == null) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ToastUtils.showMessage(tips + "响应失败");
                        }
                    });
                    return;
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (Objects.equals(parse.get("success"), "true")) {
                            ToastUtils.showMessage(tips + "上传成功");
                            SharedPreferencesUtils.saveData(UpdateRecordeActivity.this, Contants.UpdateDEVInfoState,"true");
                            Log.e("TestRecordActivity", "发送数据成功:" + parse.get("success"));
                        } else {
                            Log.e("TestRecordActivity", "发送数据失败:" + parse.get("errorCode"));
                            ToastUtils.showMessage(tips + "上传失败，错误码：" + parse.get("errorCode"));
                            SharedPreferencesUtils.saveData(UpdateRecordeActivity.this, Contants.UpdateDEVInfoState,"fail");
                        }
                    }
                });

            }
        } catch (Exception e) {
            e.printStackTrace();
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ToastUtils.showMessage(tips + "通信失败");
                }
            });
        }
    }

    private boolean conService() {
        try {
            socket = new Socket();
            //深圳服务
//            socket.connect(new InetSocketAddress("218.17.50.179", 6001), 5000);
            socket.connect(new InetSocketAddress("47.115.10.218", 15002), 5000);
            //上海服务
//            socket.connect(new InetSocketAddress("114.55.73.22", 6001), 5000);

            socket.setTcpNoDelay(true);
            socket.setKeepAlive(true);
            return socket.isConnected();
        } catch (Exception e) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ToastUtils.showMessage("服务连接失败");
                }
            });
            e.printStackTrace();
            return false;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (socket != null) {
            try {
                //断开服务器
                socket.close();
                Log.e("TestRecordActivity", "【断开服务器】");
            } catch (IOException e) {
                e.printStackTrace();
                Log.e("TestRecordActivity", "【断开服务器】异常:" + e.getMessage());
            }
        }
    }

    /**
     * 恢复出厂设置，需要系统权限，以及系统签名
     */
    public void resetSystem() {
        Intent intent = new Intent("android.intent.action.FACTORY_RESET");
        //8.0
        // intent = new Intent("android.intent.action.MASTER_CLEAR");
        //9.0
        intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
        intent.setPackage("android");

        //以上区分不同系统
        intent.putExtra("android.intent.extra.REASON", "FactoryMode");
        //是否擦除SdCard
        intent.putExtra("android.intent.extra.WIPE_EXTERNAL_STORAGE", true);
        intent.putExtra("android.intent.extra.EXTRA_WIPE_ESIMS", true);
        sendBroadcast(intent);
    }
}